package cn.jzk.mySpringSecurity_noSeparation.Config;

import cn.jzk.mySpringSecurity_noSeparation.Common.Enums.AppHttpCodeEnum;
import cn.jzk.mySpringSecurity_noSeparation.Common.Enums.UserType;
import cn.jzk.mySpringSecurity_noSeparation.Common.Exception.MyException;
import cn.jzk.mySpringSecurity_noSeparation.Entity.LoginUser;
import cn.jzk.mySpringSecurity_noSeparation.Entity.User;
import cn.jzk.mySpringSecurity_noSeparation.Mapper.MenuMapper;
import cn.jzk.mySpringSecurity_noSeparation.Mapper.UserMapper;
import jakarta.annotation.Resource;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 基于 security 的用户信息管理类
 * @author jiangzk
 * 2025/1/17  上午11:03
 */
@Component
public class DBUserDetailsManager implements UserDetailsService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private MenuMapper menuMapper;

    /**
     * 校验当前用户是否存在，若存在，则将认证成功的对象返回
     * 之后由 security 内部机制把该 Authentication 对象存入 SecurityContext 中
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        User user = userMapper.selectByUserName(username);
        if (user == null) {
            throw new UsernameNotFoundException(username);
        } else {
            // 1.进行判断当前用户是否合法
            if (!user.getStatus()){
                throw new MyException(AppHttpCodeEnum.SYSTEM_ERROR.getCode(),"当前用户是未启用状态，无法登录");
            }

            // 2.返回封装对象
            // 2.1 若是后台用户登录，需查询权限信息，以显示对应的菜单信息
            if (user.getType().equals(UserType.MANAGER.getValue())){
                // 2.2 查询当前用户的权限信息
                List<String> authorities = menuMapper.selectMenuByUserId(user.getId());
                return new LoginUser(user, authorities);
            }
            return new LoginUser(user, List.of());
        }
    }
}